package com.scalar.chiptrack.adaptor.spel;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.*;
import com.scalar.chiptrack.adaptor.dao.*;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Locale;
import java.util.Iterator;

import java.io.File;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;

/**
 * User: ChandraSekhar
 * Date: Sep 4, 2007
 * Time: 1:04:03 PM
 */
public class SPELDataParser extends JobHandler implements AdaptorConstants
{
    HashMap m_ftDataMap           = new HashMap();
    HashMap m_assemblyDataMap		= new HashMap();
    HashMap m_fgDataMap             = new HashMap();
    HashMap m_shipDataMap           = new HashMap();
    ArrayList m_shipDataList        = new ArrayList();
    private Logger m_parserLogger   = null;
    private String m_dataOutputDir  = null;
    DBTransaction dbTransaction     = null;

    
    public SPELDataParser() throws Exception
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_SPEL, WIP_TYPE_TEST);
            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
            m_parserLogger = AdaptorUtils.getDataParserLogger(m_dataOutputDir,VENDOR_NAME_SPEL);
            TestAdaptorDAO.setLogger(m_parserLogger);
            AssemblyAdaptorDAO.setLogger( m_parserLogger);
            InventoryLotDAO.setLogger( m_parserLogger );
            ShippedLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger);
        }
        catch (ScalarException e)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading SPEL output directory details from database, Exception: " + e);
            throw e;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new SPELDataParser().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_SPEL, CONSTANT_PARSER);

        File doneDestDir = new File(m_dataOutputDir + "/done");
        File wipDataoutDir = new File(m_dataOutputDir);

        File[] fileList = wipDataoutDir.listFiles();

        if ((fileList == null) || (fileList.length <= 3))
        {
            log("No file found in directory: " + wipDataoutDir);
            throw new ScalarException("No file found in directory: " + wipDataoutDir + "----\n\n");
        }

        ArrayList successFileList = new ArrayList();
        boolean success = false;

        //PARSING STARTS FROM HERE
        for (int i = 0; i < fileList.length; i++)
        {
            if (fileList[i].isDirectory() == true)
            {
                continue;
            }

            if ((fileList[i].getName() != null) && ( fileList[i].getName().trim().startsWith(SPELPOP3Adaptor.FILE_NAME_WIP) || fileList[i].getName().trim().startsWith("WIP") ) )
            {
                try
                {
                    ArrayList m_wipStatusList = parseWipInfosheet(fileList[i].getAbsolutePath());

                    if (m_wipStatusList != null && m_wipStatusList.size() > 0)
                    {
                        getWipDetails(m_wipStatusList);
                    }

                    if ( m_shipDataList != null && m_shipDataList.size() > 0 )
                    {
                        parseAllShipDataList ( m_shipDataList );
                    }
                    successFileList.add(fileList[i]);

                }
                catch( Exception e )
                {
                    success = false;
                    log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                    e.printStackTrace();
                    throw e;
                }
            }
        }

        /*Updating the Assembly Lot Information*/
        try
        {
            // Step 3
            // Save Test Information
            if (m_assemblyDataMap.isEmpty() == false)
            {
                log(" Updating Assembly Lot Information");
                AssemblyAdaptorDAO.saveAssemblyLot( null, m_assemblyDataMap.values().iterator(), WIP_TYPE_ASSEMBLY, VENDOR_NAME_SPEL );
            }
            else
            {
            	AssemblyAdaptorDAO.closeAssemblyLot(dbTransaction, WIP_TYPE_ASSEMBLY, VENDOR_NAME_SPEL );
            }
            m_assemblyDataMap.clear();
            m_assemblyDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Assembly Lot information into database: " + se);
            throw se;
        }
        
        
        /*Updating the Test Lot Information*/
        try
        {
            // Step 3
            // Save Test Information
            if (m_ftDataMap.isEmpty() == false)
            {
                log(" Updating Test Lot Information");
                TestAdaptorDAO.saveTestLot(dbTransaction, m_ftDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_SPEL);
            }
            else
            {
                TestAdaptorDAO.closeTestLot(dbTransaction, LOCATION_TYPE_FT, VENDOR_NAME_SPEL);
            }
            m_ftDataMap.clear();
            m_ftDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se);
            throw se;
        }

        try
        {
           // Saving SHIPPING Information
            if ( m_shipDataMap.isEmpty() == false )
            {
                log( "Updating Shipping Lot Information" );
                ShippedLotDAO.saveShippedLot( dbTransaction, m_shipDataMap.values().iterator() );
            }
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Shipping Lot information into database: " + se );
            throw se;
        }

        /*Updating the Finished Goods Lot Information*/
        try
        {
            // Save Finished Goods Information
            if (m_fgDataMap.isEmpty() == false)
            {
                log(" Updating Finished Goods Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_SPEL);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_SPEL);
            }
            success = true;
            m_fgDataMap.clear();
            m_fgDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Fg Lot information into database: " + se);
            throw se;
        }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_SPEL, true, true, true );

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots(VENDOR_NAME_SPEL);

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( SPELPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, SPELPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, SPELPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }//end of execute method

    /**
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parseWipInfosheet(String fileName) throws Exception
    {
        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        SPELWipStatus wipStatus     = null;
        SPELWipStatus shipStatus    = null;
        ArrayList wipList           = new ArrayList();

        try
        {
            File wipFile = new File(fileName);
            if (wipFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for SPEL Wip Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for SPEL Wip Report...");

            Workbook workbook = Workbook.getWorkbook(wipFile);
            Sheet sheet = workbook.getSheet(0);

            Cell[] row = null;

            for (int rowCount = 9; rowCount < sheet.getRows(); rowCount++)
            {
                row = sheet.getRow(rowCount);

                wipStatus = new SPELWipStatus();

                if (row.length > 1)
                {
                    if (row[1].getType().equals(CellType.EMPTY) )
                    {
                        wipStatus.setDeviceType(null);
                    }
                    else
                    {
                        wipStatus.setDeviceType(row[1].getContents().trim());
                    }
                }
                if (row.length > 2)
                {
                    if (row[2].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setPkgCode(null);
                    }
                    else
                    {
                        wipStatus.setPkgCode(row[2].getContents().trim());
                    }
                }
                if (row.length > 3)
                {
                    if (row[3].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setSpelLot(null);
                    }
                    else
                    {
                        wipStatus.setSpelLot(row[3].getContents().trim());
                    }
                }

                if (row.length >4)
                {
                    if (row[4].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setWeekCode(null);
                    }
                    else
                    {
                        wipStatus.setWeekCode(row[4].getContents().trim());
                    }
                }
                if (row.length > 5)
                {
                    if (row[5].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setCustLotNo(null);
                    }
                    else
                    {
                        wipStatus.setCustLotNo(row[5].getContents().trim());
                    }
                }
                 if (row.length > 6)
                {
                    if (row[6].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setFabLotNo(null);
                    }
                    else
                    {
                        wipStatus.setFabLotNo(row[6].getContents().trim());
                    }
                }
                if (row.length >7)
                {
                    if (row[7].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setRelQty(null);
                    }
                    else
                    {
                        wipStatus.setRelQty(row[7].getContents().trim());
                    }
                }
                if (row.length > 8)
                {
                    if (row[8].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setAssmQueueQty(null);
                    }
                    else
                    {
                        wipStatus.setAssmQueueQty(row[8].getContents().trim());
                    }
                }
                if (row.length >9)
                {
                    if (row[9].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setDsWipQty(null);
                    }
                    else
                    {
                        wipStatus.setDsWipQty(row[9].getContents().trim());
                    }
                }
                if (row.length > 10)
                {
                    if (row[10].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setDaMDWipQty(null);
                    }
                    else
                    {
                        wipStatus.setDaMDWipQty(row[10].getContents().trim());
                    }
                }
                if (row.length > 11)
                {
                    if (row[11].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setPlTFWipQty(null);
                    }
                    else
                    {
                        wipStatus.setPlTFWipQty(row[11].getContents().trim());
                    }
                }
                if (row.length > 12)
                {
                    if (row[12].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setAssmRejQty(null);
                    }
                    else
                    {
                        wipStatus.setAssmRejQty(row[12].getContents().trim());
                    }
                }
                if (row.length > 13)
                {
                    if (row[13].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setTestWipQty(null);
                    }
                    else
                    {
                        wipStatus.setTestWipQty(row[13].getContents().trim());
                    }
                }
                if (row.length > 14)
                {
                    if (row[14].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setVqcWipQty(null);
                    }
                    else
                    {
                        wipStatus.setVqcWipQty(row[14].getContents().trim());
                    }
                }
                if (row.length > 15)
                {
                    if (row[15].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setTestRejQty(null);
                    }
                    else
                    {
                        wipStatus.setTestRejQty(row[15].getContents().trim());
                    }
                }
                if (row.length > 16)
                {
                    if (row[16].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setFgShipQty(null);
                    }
                    else
                    {
                        wipStatus.setFgShipQty(row[16].getContents().trim());
                    }
                }
                if (row.length > 17)
                {
                    if (row[17].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setPoNo(null);
                    }
                    else
                    {
                        wipStatus.setPoNo(row[17].getContents().trim());
                    }
                }
                if (row.length > 18)
                {
                    if (row[18].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setPoReceiveDate(null);
                    }
                    else
                    {
                        wipStatus.setPoReceiveDate(row[18].getContents().trim());
                    }
                }
                if (row.length > 19)
                {
                    if (row[19].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setDieReceiveDate(null);
                    }
                    else if (row[19].getType().equals(CellType.DATE))
                    {
                        DateCell dc = (DateCell) row[19];
                        java.util.Date recDate = null;
                        recDate = dc.getDate();

                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                            cal.setTime(recDate);
                            recDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setDieReceiveDate(StringUtils.formatDateToString(recDate));
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(recDate);
                            recDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setDieReceiveDate(StringUtils.formatDateToString(recDate));
                        }
                    }
                }
                if (row.length > 20)
                {
                    if (row[20].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setExpectedDate(null);
                    }
                    else if (row[20].getType().equals(CellType.DATE))
                    {
                        DateCell dc = (DateCell) row[20];
                        java.util.Date expectDate = null;
                        expectDate = dc.getDate();

                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                            cal.setTime(expectDate);
                            expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setExpectedDate(StringUtils.formatDateToString(expectDate));
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(expectDate);
                            expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setExpectedDate(StringUtils.formatDateToString(expectDate));
                        }
                    }
                }
                if (row.length > 21)
                {
                    if (row[21].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setTestExpectedDate(null);
                    }
                    else if (row[21].getType().equals(CellType.DATE))
                    {
                        DateCell dc = (DateCell) row[21];
                        java.util.Date expectDate = null;
                        expectDate = dc.getDate();

                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                            cal.setTime(expectDate);
                            expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setTestExpectedDate(StringUtils.formatDateToString(expectDate));
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(expectDate);
                            expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipStatus.setTestExpectedDate(StringUtils.formatDateToString(expectDate));
                        }
                    }
                }
                
                if (row.length > 22)
                {
                    if (row[22].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.settTR(null);
                    }
                    else
                    {
                        wipStatus.settTR(row[22].getContents().trim());
                    }
                }
                if ( row.length > 23 )
                {
                    for ( int i=23; i < row.length-1; i++ )
                    {

                         if ( i%3 == 2 )
                        {
                           shipStatus = new SPELWipStatus();
                        }

                        if (row[i].getType().equals(CellType.EMPTY))
                        {
                            //wipStatus.settTR(null);
                        }
                        else if (row[i].getType().equals(CellType.DATE))
                        {
                            DateCell dc = (DateCell) row[i];
                            java.util.Date expectDate = null;
                            expectDate = dc.getDate();

                            if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                            {
                                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                                cal.setTime(expectDate);
                                expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                shipStatus.setShipDate(StringUtils.formatDateToString(expectDate));
                            }
                            else
                            {
                                Calendar cal = new GregorianCalendar();
                                cal.setTime(expectDate);
                                expectDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                shipStatus.setShipDate(StringUtils.formatDateToString(expectDate));
                            }
                        }
                        else
                        {
                            if ( i%3 == 0 )
                            {
                               //shipStatus.setShipToLocation( row[i].getContents().trim()  );
                               //shipStatus.setShipDate( row[i].getContents().trim() );
                               shipStatus.setShipQty( row[i].getContents().trim() );
                            }
                            else if ( i%3 == 1 )
                            {
                                //shipStatus.setShipDate( row[i].getContents().trim() );
                                //shipStatus.setShipQty( row[i].getContents().trim() );
                                shipStatus.setShipToLocation( row[i].getContents().trim() );
                            }
                            else if ( i%3 == 2 )
                            {
                                shipStatus.setShipDate( row[i].getContents().trim() );
                                //shipStatus.setShipQty( row[i].getContents().trim() );
                                //shipStatus.setShipToLocation( row[i].getContents().trim()  );
                            }

                            //wipStatus.settTR(row[i].getContents().trim() );
                        }

                        shipStatus.setDeviceType( wipStatus.getDeviceType() );
                        shipStatus.setCustLotNo(  wipStatus.getCustLotNo() );
                        shipStatus.setFabLotNo(  wipStatus.getFabLotNo() );
                        shipStatus.setSpelLot(   wipStatus.getSpelLot() );
                        shipStatus.setPoNo( wipStatus.getPoNo() );

                        if (shipStatus.getDeviceType() != null && shipStatus.getDeviceType().length() > 0
                            && shipStatus.getShipDate() != null && shipStatus.getShipDate().length() < 10 )
                        {
                            if ( i%3 == 0 )
                            {
                                m_shipDataList.add( shipStatus );
                            }
                        }
                    }
                }

                /*if (row.length > 21)
                {
                    if (row[21].getType().equals(CellType.EMPTY))
                    {
                        wipStatus.setRemarks(null);
                    }
                    else
                    {
                        wipStatus.setRemarks(row[21].getContents().trim());
                    }
                }*/
                if (wipStatus.getDeviceType() != null && wipStatus.getDeviceType().length() > 0)
                {
                    wipList.add(wipStatus);
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            throw ex;
        }

        return wipList;
    }

    /**
     *
     * @param wipFedList
     * @throws Exception
     */
    public void getWipDetails(ArrayList wipFedList) throws Exception
    {

        String partNumber       = null;
        String lotNumber        = null;
        String fablotNumber     = null;
        String releaseNumber    = null;
        SPELWipStatus wipStatus = null;
        TestLot testLot         = null;
        AssemblyLot assemblyLot = null;
        InventoryLot fgInventoryLot = null;
        try
        {
            Iterator wipFedIterator = wipFedList.iterator();

            while (wipFedIterator.hasNext())
            {
                wipStatus = (SPELWipStatus) wipFedIterator.next();

                partNumber      = wipStatus.getDeviceType();
                lotNumber       = wipStatus.getSpelLot();
                fablotNumber    = wipStatus.getFabLotNo();
                releaseNumber   = wipStatus.getCustLotNo();

                if ( releaseNumber != null && releaseNumber.length() < 7 && releaseNumber.startsWith("0") == false )
                {
                    releaseNumber = "0"+ releaseNumber;
                }

                if ( lotNumber == null )
                {
                    lotNumber = fablotNumber;
                }
                if ( fablotNumber == null )
                {
                    fablotNumber = lotNumber;
                }

                if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() > 0)
                {

                    if ( releaseNumber != null && releaseNumber.length() > 0 )
                    {
                        if ( releaseNumber.indexOf("-") != -1 )
                        {
                            releaseNumber = releaseNumber.substring(0, releaseNumber.indexOf("-") );
                        }

                        int releaseCount = AdaptorDAO.getApprovedAssemblyReleaseLot( releaseNumber, partNumber, VENDOR_NAME_SPEL );

                        if ( releaseCount > 0 )
                        {
                            AdaptorDAO.updateAssemblyReleaseStatus( releaseNumber );
                        }
                    }

                    if (   wipStatus.getTestWipQty() != null && wipStatus.getTestWipQty().equalsIgnoreCase("0") == false
                        || wipStatus.getVqcWipQty()  != null && wipStatus.getVqcWipQty().equalsIgnoreCase("0")  == false ) 
                    {

                        testLot = (TestLot) m_ftDataMap.get(partNumber + lotNumber + fablotNumber);

                        if (testLot == null)
                        {
                            testLot = new TestLot(VENDOR_NAME_SPEL);
                            m_ftDataMap.put( partNumber + lotNumber + fablotNumber, testLot);
                        }

                        if (wipStatus.getTestWipQty() != null && wipStatus.getTestWipQty().equalsIgnoreCase("0") == false)
                        {
                        	testLot = (TestLot) m_ftDataMap.get(partNumber + lotNumber + fablotNumber);
                        	
                        	if( testLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			testLot.setQtyIn( ( Integer.parseInt( testLot.getQtyIn() ) + Integer.parseInt( wipStatus.getTestWipQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			testLot.setQtyIn( wipStatus.getTestWipQty() );
								}
                        	}
                        	else
                        	{
                        		testLot.setQtyIn( wipStatus.getTestWipQty() );	
                        	}

                            if ( testLot.getStage() != null )
                            {
                                testLot.setStage ( testLot.getStage() +", TEST") ;
                            }
                            else
                            {
                                testLot.setStage("TEST");
                            }

                        }
                        
                        if (wipStatus.getVqcWipQty() != null && wipStatus.getVqcWipQty().equalsIgnoreCase("0") == false)
                        {
                        	testLot = (TestLot) m_ftDataMap.get(partNumber + lotNumber + fablotNumber);
                        	if( testLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			testLot.setQtyIn( ( Integer.parseInt( testLot.getQtyIn() ) + Integer.parseInt( wipStatus.getVqcWipQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			testLot.setQtyIn( wipStatus.getVqcWipQty() );
								}
                        	}
                        	else
                        	{
                        		testLot.setQtyIn( wipStatus.getVqcWipQty() );	
                        	}

                            if ( testLot.getStage() != null )
                            {
                                testLot.setStage ( testLot.getStage() +", VQC") ;
                            }
                            else
                            {
                                testLot.setStage("VQC");
                            }

                        }

                        testLot.setLotNumber(lotNumber);
                        testLot.setPartNumber(partNumber);
                        testLot.setFabLotNumber(fablotNumber);
                        testLot.setPackageType(wipStatus.getPkgCode());
                        testLot.setCategory(LOT_CATEGORY_TYPE_PROD);
                        testLot.setPoNumber(wipStatus.getPoNo());
                        testLot.setPsType(LOCATION_TYPE_FT);
                        testLot.setDateIn(wipStatus.getDieReceiveDate());
                        testLot.setExpecetedDate(wipStatus.getTestExpectedDate() );
                        testLot.setStatus(LOT_STATUS_RUNNING);
                        testLot.setVendorLot( releaseNumber );
                    }
                    
                    if( wipStatus.getAssmQueueQty()!= null && wipStatus.getAssmQueueQty().equalsIgnoreCase("0")== false
                        || wipStatus.getDsWipQty()!= null && wipStatus.getDsWipQty().equalsIgnoreCase("0")== false
                        || wipStatus.getDaMDWipQty()!= null && wipStatus.getDaMDWipQty().equalsIgnoreCase("0")== false
	                    || wipStatus.getPlTFWipQty()!= null && wipStatus.getPlTFWipQty().equalsIgnoreCase("0")== false )
                    {

                        assemblyLot = (AssemblyLot) m_assemblyDataMap.get(partNumber + lotNumber + fablotNumber);
                        
                    	if (assemblyLot == null)
                        {
                    		assemblyLot = new AssemblyLot( VENDOR_NAME_SPEL );
                    		m_assemblyDataMap.put( partNumber + lotNumber + fablotNumber, assemblyLot);
                        }

                        if ( wipStatus.getAssmQueueQty()!= null && wipStatus.getAssmQueueQty().equalsIgnoreCase("0")== false )
                        {
                            assemblyLot = (AssemblyLot) m_assemblyDataMap.get(partNumber + lotNumber + fablotNumber);

                        	if( assemblyLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			assemblyLot.setQtyIn( ( Integer.parseInt( assemblyLot.getQtyIn() ) + Integer.parseInt( wipStatus.getAssmQueueQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			assemblyLot.setQtyIn( wipStatus.getAssmQueueQty() );
								}
                        	}
                        	else
                        	{
                        		assemblyLot.setQtyIn( wipStatus.getAssmQueueQty() );
                        	}
                        	if ( assemblyLot.getStage() != null )
                            {
                                assemblyLot.setStage ( assemblyLot.getStage() +", In Queue") ;
                            }
                            else
                            {
                                assemblyLot.setStage("In Queue");
                            }
                        }
                        if (wipStatus.getDsWipQty() != null && wipStatus.getDsWipQty().equalsIgnoreCase("0") == false)
                        {
                        	assemblyLot = (AssemblyLot) m_assemblyDataMap.get(partNumber + lotNumber + fablotNumber);

                        	if( assemblyLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			assemblyLot.setQtyIn( ( Integer.parseInt( assemblyLot.getQtyIn() ) + Integer.parseInt( wipStatus.getDsWipQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			assemblyLot.setQtyIn( wipStatus.getDsWipQty() );
								}
                        	}
                        	else
                        	{
                        		assemblyLot.setQtyIn( wipStatus.getDsWipQty() );	
                        	}
                        	if ( assemblyLot.getStage() != null )
                            {
                                assemblyLot.setStage ( assemblyLot.getStage() +", DS") ;
                            }
                            else
                            {
                                assemblyLot.setStage("DS");
                            }
                        }
                        
                        if (wipStatus.getDaMDWipQty() != null && wipStatus.getDaMDWipQty().equalsIgnoreCase("0") == false)
                        {
                        	assemblyLot = (AssemblyLot) m_assemblyDataMap.get(partNumber + lotNumber + fablotNumber);
                        	if( assemblyLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			assemblyLot.setQtyIn( ( Integer.parseInt( assemblyLot.getQtyIn() ) + Integer.parseInt( wipStatus.getDaMDWipQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			assemblyLot.setQtyIn( wipStatus.getDaMDWipQty() );
								}
                        	}
                        	else
                        	{
                        		assemblyLot.setQtyIn( wipStatus.getDaMDWipQty() );	
                        	}

                            if ( assemblyLot.getStage() != null )
                            {
                                assemblyLot.setStage ( assemblyLot.getStage() +", DA-MD") ;
                            }
                            else
                            {
                                assemblyLot.setStage("DA-MD");
                            }

                        }

                        if (wipStatus.getPlTFWipQty() != null && wipStatus.getPlTFWipQty().equalsIgnoreCase("0") == false)
                        {
                        	assemblyLot = (AssemblyLot) m_assemblyDataMap.get(partNumber + lotNumber + fablotNumber);
                        	if( assemblyLot.getQtyIn() != null )
                        	{
                        		try
								{
                        			assemblyLot.setQtyIn( ( Integer.parseInt( assemblyLot.getQtyIn() ) + Integer.parseInt( wipStatus.getPlTFWipQty() ) ) + "" );
								}
                        		catch(Exception e)
								{
                        			assemblyLot.setQtyIn( wipStatus.getPlTFWipQty() );
								}
                        	}
                        	else
                        	{
                        		assemblyLot.setQtyIn( wipStatus.getPlTFWipQty() );	
                        	}

                            if ( assemblyLot.getStage() != null )
                            {
                                assemblyLot.setStage ( assemblyLot.getStage() +", PL-TF") ;
                            }
                            else
                            {
                                assemblyLot.setStage("PL-TF");
                            }
                        }
                        
                        assemblyLot.setDeviceName( partNumber );
                        assemblyLot.setPackageType( wipStatus.getPkgCode() );
                        assemblyLot.setLotNumber( lotNumber );
                        assemblyLot.setDateCode( wipStatus.getWeekCode() );
                        assemblyLot.setPONumber( wipStatus.getPoNo() );
                        assemblyLot.setStatus( LOT_STATUS_RUNNING );
                        assemblyLot.setFabLotNumber( fablotNumber );
                        assemblyLot.setCategory( LOT_CATEGORY_TYPE_PROD );
                        assemblyLot.setDateIn( wipStatus.getDieReceiveDate() );
                        assemblyLot.setExpectedDateOut( wipStatus.getExpectedDate() );
                        assemblyLot.setVendorLotNumber( releaseNumber );    // Release number Considering as Vendor Lot No
                    }
                   //FG LOTS
                    if ( wipStatus.getFgShipQty() != null && wipStatus.getFgShipQty().equalsIgnoreCase("0") == false )
                    {
                        log(lotNumber + "In FG");

                        fgInventoryLot = (InventoryLot)m_fgDataMap.get( partNumber + lotNumber + fablotNumber );

                        if ( fgInventoryLot == null )
                        {
                            fgInventoryLot = new InventoryLot( VENDOR_NAME_SPEL, LOCATION_TYPE_FG );
                            m_fgDataMap.put( partNumber + lotNumber + fablotNumber, fgInventoryLot );
                        }

                        fgInventoryLot.setPartNumber( partNumber );
                        fgInventoryLot.setLotNumber( lotNumber );
                        fgInventoryLot.setQtyIn( wipStatus.getFgShipQty() );
                        fgInventoryLot.setDateIn( wipStatus.getDieReceiveDate());
                        fgInventoryLot.setExpectedDate( wipStatus.getExpectedDate() );
                        fgInventoryLot.setFabLotNumber( fablotNumber );
                        fgInventoryLot.setPkgType( wipStatus.getPkgCode() );
                        fgInventoryLot.setStatus( LOT_STATUS_RUNNING );
                        fgInventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                        fgInventoryLot.setVendorLot( releaseNumber );
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the SPEL Wip Details" + e);
            System.out.println("ERROR!ERROR! While parsing the SPEL Wip Details" + e);
            throw e;
        }
    }

   private void parseAllShipDataList( ArrayList shipdataList ) throws Exception
   {
       SPELWipStatus shipReport = null;
       ShippedLot shippedLot = null;

       String partNumber    = null;
       String lotNumber     = null;
       String shipDate      = null;

       Iterator iterator = shipdataList.iterator();

       while ( iterator.hasNext() )
       {
           shipReport = ( SPELWipStatus ) iterator.next();

           partNumber   = shipReport.getDeviceType();
           lotNumber    = shipReport.getSpelLot();
           shipDate     = shipReport.getShipDate();

           if ( partNumber != null && partNumber.length() > 0 && lotNumber != null && lotNumber.length() > 0 )
           {
                shippedLot = ( ShippedLot ) m_shipDataMap.get( partNumber + lotNumber + shipDate );

                if ( shippedLot == null )
                {
                    shippedLot = new ShippedLot( VENDOR_NAME_SPEL, WIP_TYPE_TEST );
                    m_shipDataMap.put( partNumber + lotNumber + shipDate , shippedLot );
                }
                int quantity = 0;
                if ( shippedLot.getShipQty() != null )
                {
                   try
                   {
                       quantity = Integer.parseInt( shippedLot.getShipQty() );
                   }
                   catch ( NumberFormatException ignore )
                   {
                   }
                   try
                   {
                       quantity += Integer.parseInt( shipReport.getShipQty() );
                   }
                   catch ( NumberFormatException ignore )
                   {
                   }
                }
                else
                {
                   try
                   {
                       quantity = Integer.parseInt( shipReport.getShipQty() );
                   }
                   catch ( NumberFormatException ignore )
                   {
                   }
                }
                if ( quantity > 0 )
                {
                    shippedLot.setLotNumber( lotNumber );
                    shippedLot.setPartNumber( partNumber );
                    shippedLot.setShipDate( shipReport.getShipDate() );
                    shippedLot.setShipQty( quantity +"" );
                    shippedLot.setCustomerPO( shipReport.getPoNo() );
                    shippedLot.setNextLocation( shipReport.getShipToLocation() );
                    shippedLot.setProcessType( WIP_TEST_TYPE_FT );
                    shippedLot.setFabLotNumber( shipReport.getFabLotNo() );
                }
           }

       }
   }

    private void log(String message)
    {
        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }

}
